package com.haier.unpackshell;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import com.haier.crypt.CryptUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class UnPackShellUtils {
    public static String UNPACK_SHELL_FILE_NAME = "CaculateSDK-debug-unpack.apk";
    public static String TO_UNPACK_FILE_NAME = "sdk.zip";

    public static boolean unpackSdk(String sdkPath, String targetPath) {
        File file = new File(sdkPath);
        if (!file.exists()) return false;
        File resFile = CryptUtils.decryptFile(file, targetPath, UNPACK_SHELL_FILE_NAME, CryptUtils.secretKey);
        if (!resFile.exists()) return false;
        return true;
    }

    public static boolean unpackSdk(Context context) {
        String sdkFilePath = context.getCacheDir().getPath() + TO_UNPACK_FILE_NAME;
        cpAssertToFiles(context, TO_UNPACK_FILE_NAME, sdkFilePath);
        File file = new File(sdkFilePath);
        if (!file.exists()) return false;
        Log.e("XXX", "file size " + file.length());
        File resFile = CryptUtils.decryptFile(file, context.getCacheDir().getPath(), UNPACK_SHELL_FILE_NAME, CryptUtils.secretKey);
        if (!resFile.exists()) return false;
        Log.e("XXX", "resFile size " + resFile.length());
        return true;
    }

    public static void cpAssertToFiles(Context context, String fileName, String destPath) {
        File file = new File(destPath);
        if (file.exists()) file.delete();
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        AssetManager assetManager = context.getAssets();
        try (InputStream inputStream = assetManager.open(fileName);
             FileOutputStream outputStream = new FileOutputStream(file)) {
            if (inputStream == null) return;

            byte buf[] = new byte[inputStream.available()];
            int len;
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
